package com.tiancheng.trade.commom.core.utils;

import java.security.SecureRandom;
import java.util.*;

/**
 * 字符序列工具
 *
 * @author kellen
 * @date 2024/11/10
 */
public class RandomCharSequenceUtil {

    private static final String UPPER_CASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String LOWER_CASE = "abcdefghijklmnopqrstuvwxyz";
    private static final String NUMBERS = "0123456789";
    private static final String ALL_CHAR_TYPES = UPPER_CASE + LOWER_CASE + NUMBERS;
    private static final int PASSWORD_LENGTH = 32;
    private static final SecureRandom random = new SecureRandom();

    private static final char[] charArray = "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM".toCharArray();

    /**
     * 获取指定长度随机字符串，可包含数字、大小写字母
     *
     * @param length 长度
     * @return {@link String}
     */
    public static String getRandomCharSequence(int length) {
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < length; i++) {
            str.append(charArray[(int) (Math.random() * charArray.length)]);
        }
        return str.toString();
    }

    /**
     * 随机字符串，包含大写、小写、数字三种
     * @return
     */
    public static String generateRandomString() {
        StringBuilder sb = new StringBuilder(PASSWORD_LENGTH);
        Set<Character> chars = new HashSet<>();

        // 确保每种字符类型至少有一个
        sb.append(UPPER_CASE.charAt(random.nextInt(UPPER_CASE.length())));
        sb.append(LOWER_CASE.charAt(random.nextInt(LOWER_CASE.length())));
        sb.append(NUMBERS.charAt(random.nextInt(NUMBERS.length())));
        chars.add(sb.charAt(0));
        chars.add(sb.charAt(1));
        chars.add(sb.charAt(2));

        // 填充剩余的字符直到达到32位长度
        while (sb.length() < PASSWORD_LENGTH) {
            char c = ALL_CHAR_TYPES.charAt(random.nextInt(ALL_CHAR_TYPES.length()));
            if (!chars.contains(c)) { // 确保不重复使用已经选择的字符（可选，但会增加随机性）
                sb.append(c);
                chars.add(c);
            }
        }

        // 为了满足题目要求，我们可以打乱字符串以确保随机性，但这会增加复杂性。如果需要，可以使用以下方法：
        sb = new StringBuilder(shuffleString(sb.toString()));
        return sb.toString();
    }

    // 可选：打乱字符串的方法（如果你希望最终的字符串顺序是随机的）
    private static String shuffleString(String str) {
        List<Character> list = new ArrayList<>();
        for (char ch : str.toCharArray()) {
            list.add(ch);
        }
        Collections.shuffle(list, random);
        StringBuilder shuffledStr = new StringBuilder(list.size());
        for (char ch : list) {
            shuffledStr.append(ch);
        }
        return shuffledStr.toString();
    }


}
